from appengine_django.models import BaseModel
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms

import logging

import utils

# Create your models here.
class FlickrOption(BaseModel):
    api_key = db.StringProperty('Flickr API Key')
    #secret_key = db.StringProperty('Flickr secret Key')
    #user_id = db.StringProperty('Flickr User Id')
    #set_id = db.StringProperty('Flickr Set Id')
    
    class Meta:
        verbose_name_plural = 'FlickrOption'

class Photo(BaseModel):
    photo_id = db.StringProperty('Flickr Photo Id')
    title = db.StringProperty()
    body = db.TextProperty()
    is_published = db.BooleanProperty(default=True)
    pub_date = db.DateTimeProperty(auto_now_add=True)
    thumb_info = db.TextProperty('Thumb Info')
    photo_info = db.TextProperty('Photo Info')    
    exif_info = db.TextProperty('Exif Info')    
    
    def __unicode__(self):
        return self.title

    def get_flickrOption(self):
        try:
            flickrOption = FlickrOption.gql("LIMIT 1")
            flickrOption = flickrOption[0]
            api_key = flickrOption.api_key
            #secret  = flickrOption.secret_key
            #userid  = flickrOption.user_id
            #setid   = flickrOption.set_id            
        except:
            api_key = ''
            #secret  = ''
            #userid  = ''
            #setid   = ''        
        #return dict(api_key=api_key, secret_key=secret, userid = userid, setid = setid)
        return dict(api_key=api_key)

    def put(self):        
        if self.title is None:
            flickrOption = self.get_flickrOption()
            if flickrOption['api_key'] != '':
                try:
                    logging.info(self.photo_id)
                    pinfo            = utils.get_photo_info(flickrOption['api_key'],self.photo_id)                    
                    self.title      = pinfo['title']
                    self.body       = pinfo['desc']
                    self.exif_info  = str(pinfo['exif']) #dict vals can't be stored into textproperty
                    self.thumb_info = str(pinfo['thumb'])
                    self.photo_info = str(pinfo['photo'])                    
                    #self.exif_info = "||".join(["%s=%s" % (k, v) for k, v in photo_info['exif'].items()])
                    #self.thumb_info = "||".join(["%s=%s" % (k, v) for k, v in photo_info['thumb'].items()])
                    #self.photo_info = "||".join(["%s=%s" % (k, v) for k, v in photo_info['photo'].items()])
                except:
                    pass
        super(Photo,self).put()        
    class Meta:
        verbose_name_plural = 'photos'
        ordering = ('-pub_date',)
        get_latest_by = 'pub_date' 